package com.apt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.apt.common.AptException;
import com.apt.common.DBUtility;
import com.apt.domain.UserTest;
import com.apt.model.AptTest;

public class TestMasterDao extends BaseConnection {

	public TestMasterDao(Connection con) {
		super(con);

	}

	public List<AptTest> getAptTestDetails() throws AptException {
		List<AptTest> tests = new ArrayList<AptTest>();
		try {

			PreparedStatement ps = connection
					.prepareStatement("SELECT TEST_ID,NAME,DESCRIPTION,TOTAL_QUESTIONS,DISABLED,DURATION FROM TEST_MASTER");
			
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {

				AptTest apt = new AptTest(String.valueOf(rs.getInt(1)),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getInt(6));
				tests.add(apt);

			}
			rs.close();
			//System.out.println("No Of Tests:" + tests.size());

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException("Unable to query the database to get the list of available tests");
							

		} finally {
			DBUtility.cleanUp(connection);

		}

		return tests;

	}
	
	public int getTestDuration(int testId) throws AptException {
		
		try {

			PreparedStatement ps = connection
					.prepareStatement("SELECT DURATION FROM TEST_MASTER WHERE TEST_ID=?");
			ps.setInt(1,testId);
			
			ResultSet rs = ps.executeQuery();
			int duration = 0;
			if (rs.next()) {

				
				duration =  rs.getInt(1);
				

			}
			ps.close();
			if(duration == 0)
			{
				throw new AptException("Duration time  is unspecified for test:" + testId);
				
			}
			return duration;
			

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException("Unable to query the database to get the duration of the test for the testId:"+testId);
							

		} finally {
			
			DBUtility.cleanUp(connection);

		}

		

	}
	
	public void updateTestDetails(List<AptTest> updateList) throws AptException
	{
		
		try {

			PreparedStatement ps = connection
					.prepareStatement("UPDATE TEST_MASTER SET NAME = ?,DESCRIPTION = ?,DISABLED = ?,TOTAL_QUESTIONS = ?, DURATION =? WHERE TEST_ID = ?");
			for (AptTest each : updateList) {

				ps.setString(1, each.getTestName());
				ps.setString(2, each.getTestDescription());
				ps.setString(3, each.getDisabled());
				ps.setInt(4, each.getTotalNumberOfQuesions());
				ps.setInt(5, each.getDuration());
				ps.setInt(6,Integer.parseInt(each.getTestId()));
				ps.addBatch();

			}
			ps.executeBatch();
			connection.commit();
			ps.close();

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException(
					"Unable to update the Test Details");
							

		} finally {

			DBUtility.cleanUp(connection);

		}
		
		
	}

}
